//
//  CrmFilterStaffVC.m
//  New_Runway
//
//  Created by mack on 2018/2/27.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "CrmFilterStaffVC.h"
#import "CarSetListCell.h"
#import "UserModel.h"
#import "PickCustomView.h"
#import "PickDateView.h"
#import "CrmIsArriveShopCell.h"
#import "CrmCancelCell.h"


@interface CrmFilterStaffVC ()<UITableViewDelegate,UITableViewDataSource,PickerDateViewDelegate,CustomPickViewDelegate>
@property(nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) NSMutableArray *userArray;
@property (nonatomic, assign) BOOL isShowDay;
@property (nonatomic, strong) NSMutableDictionary *params;
@property (nonatomic, strong) NSMutableDictionary *allocateDic;


@end

@implementation CrmFilterStaffVC
{
    NSString *_dateStr;
    NSString *_peopleId;
}
-(NSMutableDictionary *)allocateDic{
    if (!_allocateDic) {
        _allocateDic = [[NSMutableDictionary alloc] init];
    }
    return _allocateDic;
}
-(NSMutableDictionary *)params{
    if (!_params) {
        
        _params = [[NSMutableDictionary alloc] init];
    }
    return _params;
    
}
-(NSMutableArray *)userArray{
    if (!_userArray) {
        _userArray = [[NSMutableArray alloc] init];
        
    }
    return _userArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    if (self.type == kFilterStaffVCTypeDistribute) {
        self.navigationBarView.titleLabel.text = @"分配";
        [self.allocateDic setObject:self.customerShopId forKey:@"customerShopId"];
    }else if (self.type == kFilterStaffVCTypeFilter){
        self.navigationBarView.titleLabel.text = @"筛选";
    }
    self.view.backgroundColor = kColorWhite();
    [self initTableview];
    if (self.type == kCRMListViewTypeNewToAssigned) {
        self.navigationBarView.rightItem.hidden = YES;
        
    }else{
        self.navigationBarView.rightItem.hidden = NO;
        [self.navigationBarView.rightItem setTitle:@"重置" forState:UIControlStateNormal];
    }
    [self.params setObject:@(NO) forKey:@"isReach"];
}

-(void)rightItemClick{
    
    if (self.type != kFilterStaffVCTypeFilterNoFollower) {
        [self.params setObject:@"" forKey:@"followerId"];
    }
    
    [self.params setObject:@"" forKey:@"isReach"];
    self.reset = kFilterStaffVCReset;
    _peopleName = @"";
    [self.tableview reloadData];
    
}
-(void)initTableview{
    kSelfWeak;
    self.tableview = [[UITableView alloc] init];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    _tableview.estimatedRowHeight = 0;
    _tableview.estimatedSectionHeaderHeight = 0;
    _tableview.estimatedSectionFooterHeight = 0;
    if (@available(iOS 11.0, *)) {
        self.tableview.contentInsetAdjustmentBehavior = UIApplicationBackgroundFetchIntervalNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = false;
    }
    self.tableview.backgroundColor = kColorWhite();
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableview registerClass:[CarSetListCell class] forCellReuseIdentifier:@"CarSetListCell"];
    [self.tableview registerNib:[UINib nibWithNibName:@"MineMessageCell" bundle:nil] forCellReuseIdentifier:@"MineMessageCell"];
    [self.tableview registerNib:[UINib nibWithNibName:@"CrmIsArriveShopCell" bundle:nil] forCellReuseIdentifier:@"CrmIsArriveShopCell"];
    [self.tableview registerNib:[UINib nibWithNibName:@"CrmCancelCell" bundle:nil] forCellReuseIdentifier:@"CrmCancelCell"];
    
    [self.view addSubview:self.tableview];
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).mas_equalTo(self.navH );
        make.bottom.equalTo(weakSelf.view).mas_equalTo(-self.BotH);
        make.left.right.equalTo(weakSelf.view);
    }];
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 2) {
        return 120;
    }
    
    if (self.type == kFilterStaffVCTypeFilterNoFollower) {
        if (indexPath.row == 0) {
            return 0;
        } else {
            return 50;
        }
    } else  {
        return 50;
    }
    return 0;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 3;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0 ) {
        CarSetListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CarSetListCell"];
        [cell.rightImage setImage:[UIImage imageNamed:@"up"] forState:UIControlStateNormal];
        cell.centerTF.userInteractionEnabled = NO;
        cell.centerLabel.hidden = YES;
        cell.switchButton.hidden = YES;
        cell.StarL.hidden = NO;
        cell.centerTF.text = _peopleName;
        cell.selectionStyle = UITableViewCellSeparatorStyleNone;
        cell.centerTF.placeholder = @"请选择员工";
        cell.label.text = @"选择员工";
        return cell;
    }
    
    if (indexPath.row == 1){
        
        if (self.type == kCRMListViewTypeNewToAssigned) {
            CarSetListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CarSetListCell"];
            [cell.rightImage setImage:[UIImage imageNamed:@"up"] forState:UIControlStateNormal];
            cell.centerTF.userInteractionEnabled = NO;
            cell.centerLabel.hidden = YES;
            cell.switchButton.hidden = YES;
            cell.StarL.hidden = NO;
            cell.centerTF.text = _dateStr;
            cell.selectionStyle = UITableViewCellSeparatorStyleNone;
            cell.centerTF.placeholder = @"请选择日期";
            cell.label.text = @"跟进日期";
            
            return cell;
        }else{
            CrmIsArriveShopCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CrmIsArriveShopCell"];
            cell.iscrm = YES;
            kSelfWeak;
            if (self.reset == kFilterStaffVCIsReachAll) {
                cell.isNoB.selected = NO;
                cell.isYesB.selected = NO;
                [cell.isYesB setImage:[UIImage imageNamed:@"crm_seleted_n"] forState:UIControlStateNormal];
                [cell.isNoB setImage:[UIImage imageNamed:@"crm_seleted_n"] forState:UIControlStateNormal];
                
            }else if (self.reset == kFilterStaffVCIsReachNo){
                cell.isNoB.selected = YES;
                cell.isYesB.selected = NO;
                [cell.isYesB setImage:[UIImage imageNamed:@"crm_seleted_n"] forState:UIControlStateNormal];
                [cell.isNoB setImage:[UIImage imageNamed:@"crm_seleted_s"] forState:UIControlStateSelected];
            }else if (self.reset == kFilterStaffVCIsReachYes){
                cell.isNoB.selected = NO;
                cell.isYesB.selected = YES;
                [cell.isYesB setImage:[UIImage imageNamed:@"crm_seleted_s"] forState:UIControlStateSelected];
                [cell.isNoB setImage:[UIImage imageNamed:@"crm_seleted_n"] forState:UIControlStateNormal];
                
            } else if (self.reset == kFilterStaffVCReset) {
                cell.isNoB.selected = NO;
                cell.isYesB.selected = NO;
                [cell.isNoB setImage:[UIImage imageNamed:@"crm_seleted_n"] forState:UIControlStateNormal];
                [cell.isYesB setImage:[UIImage imageNamed:@"crm_seleted_n"] forState:UIControlStateNormal];
            }
            
            return cell;
        }
    }
    
    CrmCancelCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CrmCancelCell"];
    kSelfWeak;
    cell.ClicBlock = ^(NSInteger index) {
        
        if (index == 1){
            if (weakSelf.type == kCRMListViewTypeNewToAssigned) {
                [weakSelf allocateCustomer];
            }else{
                
                UITableViewCell *cell = [weakSelf.tableview cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
                
                if ([cell isKindOfClass:[CrmIsArriveShopCell class]]) {
                    
                    CrmIsArriveShopCell *newCell = (CrmIsArriveShopCell *)cell;
                    
                    if (newCell.isYesB.selected == YES) {
                        weakSelf.reset = kFilterStaffVCIsReachYes;
                        [weakSelf.params setObject:@(1) forKey:@"isReach"];
                    } else if (newCell.isNoB.selected == YES) {
                        weakSelf.reset = kFilterStaffVCIsReachNo;
                        [weakSelf.params setObject:@(0) forKey:@"isReach"];
                    } else {
                        weakSelf.reset = kFilterStaffVCIsReachAll;
                        [weakSelf.params setObject:@"" forKey:@"isReach"];
                    }
                }
                weakSelf.chooseOkBlock(weakSelf.params,weakSelf.reset,weakSelf.peopleName);
                [weakSelf.navigationController popViewControllerAnimated:YES];
                
            }
        }else{
            
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
        
    };
    
    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        [self LoadStaffInfo];
    }else if (indexPath.row == 1){
        
        if (self.type == kCRMListViewTypeNewToAssigned) {
            [self CreatDateChoose];
            
        }
    }
    
}

//获取员工
-(void)LoadStaffInfo{
    
    
    NSDictionary *params = @{@"shopId":[NRWCarUser sharedUser].shopId,
                             @"marketId":[NRWCarUser sharedUser].marketId
                             };
    [SVProgressHUD show];
    [YQNetworking postWithUrl:[NSString stringWithFormat:@"%@%@",Api,staffInfoApi] refreshRequest:YES cache:NO params:params progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        [self.userArray removeAllObjects];
        if ([response[@"code"] isEqual:@1]) {
            NSArray *array = response[@"result"];
            NSMutableArray *userNames= [[NSMutableArray alloc] init];
            for (NSDictionary *dic  in array) {
                UserModel *model = [[UserModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.userArray addObject:model];
                [userNames addObject:model.userName];
                
            }
            [self creatChoose:userNames tag:2];
        }
        [SVProgressHUD dismiss];
        
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];

        [SVProgressHUD dismiss];
        
    }];
    
}

//单个信息
-(void)creatChoose:(NSMutableArray *)titles tag:(NSInteger)tag{
    
    
    PickCustomView *pickerSingle = [[PickCustomView alloc]init];
    pickerSingle.tag = tag;
    pickerSingle.pickerViewHeight = 300;
    [pickerSingle setDataArray:titles];
    [pickerSingle setDefalutSelectRowStr:titles[0]];
    [pickerSingle setDelegate:self];
    [pickerSingle show];
    [self.view endEditing:YES];
}
-(void)customPickView:(PickCustomView *)customPickView selectedTitle:(NSString *)selectedTitle index:(NSInteger)index{
    _peopleName = selectedTitle;
    UserModel *model = self.userArray[index];
    _peopleId = model.userId;
    [self.params setObject:_peopleId forKey:@"followerId"];
    [self.allocateDic setObject:_peopleName forKey:@"followerName"];
    [self.allocateDic setObject:_peopleId forKey:@"followerId"];
    
    [self.tableview reloadData];
    
}
//时间
-(void)CreatDateChoose{
    
    _isShowDay=YES;
    PickDateView *pickerDate = [[PickDateView alloc]init];
    
    pickerDate.pickerViewHeight = 300;
    //    [pickerDate setIsAddYetSelect:YES];//是否显示至今选项
    [pickerDate setIsShowDay:_isShowDay];//是否显示日信息
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    // 获取当前日期
    NSDate* dt = [NSDate date];
    // 指定获取指定年、月、日、时、分、秒的信息
    unsigned unitFlags = NSCalendarUnitYear |
    NSCalendarUnitMonth |  NSCalendarUnitDay |
    NSCalendarUnitHour |  NSCalendarUnitMinute |
    NSCalendarUnitSecond | NSCalendarUnitWeekday;
    NSDateComponents* comp = [gregorian components: unitFlags fromDate:dt];
    [pickerDate setDefaultTSelectYear:comp.year defaultSelectMonth:comp.month defaultSelectDay:comp.day];//设定默认显示的日期
    [pickerDate setDelegate:self];
    [pickerDate show];
}

-(void)pickerDateView:(BasePickView *)pickerDateView selectYear:(NSInteger)year selectMonth:(NSInteger)month selectDay:(NSInteger)day{
    
    if (_isShowDay==YES) {
        _dateStr = [NSString stringWithFormat:@"%ld-%ld-%ld",year,month,day];
    }else{
        _dateStr = [NSString stringWithFormat:@"%ld-%ld月",year,month];
    }
    [self.allocateDic setObject:_dateStr forKey:@"nextFollowDatetime"];
    [self.tableview reloadData];
}
-(void)allocateCustomer{
    
    NSString *nameString = [self.allocateDic objectForKey:@"followerName"];
    if ([nameString isKindOfClass:[NSString class]] || nameString == nil) {
        if (isEmptyOrNilString(nameString)) {
            [ShowMessage showHintMessage:@"员工不能为空" duration:1 withRemindId:remindWarning];
            return;
        }
    }
    
    if (self.type == kCRMListViewTypeNewToAssigned) {
        NSString *followTime = [self.allocateDic objectForKey:@"nextFollowDatetime"];
        if ([followTime isKindOfClass:[NSString class]] || followTime == nil) {
            if (isEmptyOrNilString(followTime)) {
                [ShowMessage showHintMessage:@"跟进日期不能为空" duration:1 withRemindId:remindWarning];
                return;
            }
        }
    }
    
    NSString *url = [NSString stringWithFormat:@"%@%@",CRMContextApi,allocteCustomerApi];
    [YQNetworking postWithUrl:url refreshRequest:YES cache:NO params:self.allocateDic progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        if ([response[@"code"] isEqual:@1] ) {
            
            [self.navigationController popViewControllerAnimated:YES];
            self.successBlock();
        } else {
            
            [SVProgressHUD showWithStatus:response[@"msg"] dismissDelay:1];
        }
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];

    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
